package com.example.ujsfish.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ujsfish.R;
import com.example.ujsfish.adapter.PoolPointAdapter;
import com.example.ujsfish.model.ObstaclesPoint;
import com.example.ujsfish.model.poolMap.PoolPoint;
import com.example.ujsfish.utils.AppNetService;
import com.example.ujsfish.model.manual.ManualControlData;
import com.example.ujsfish.model.monitor.Data;
import com.example.ujsfish.model.monitor.JsonRootBean;
import com.example.ujsfish.model.ship.PoolName;
import com.example.ujsfish.utils.DeviceName;
import com.example.ujsfish.utils.RetrofitManager;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class PaintMap extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private static final String TAG = "PaintMap";
    RetrofitManager myRetrofitManager = RetrofitManager.getInstance();
    Retrofit myRetrofit = RetrofitManager.getRetrofit();
    AppNetService appNetService = myRetrofitManager.getApiService(AppNetService.class);

    private ManualControlData.ManualBody manualBody = ManualControlData.getManualBody();

    String id;

    String poolName;
    String obsName;
    int poolCount;
    int obsCount;

    private List<PoolPoint> poolList = new ArrayList<>(); //池塘顶点
    private List<PoolPoint> obsList = new ArrayList<>();  //池塘障碍点

    private Button btn_insert_poolPoint;
    private Button btn_insert_obsPoint;
    private Button btn_subPoint;
    private Button btn_subObs;
    private Button createPool;
    private Button createObs;

    private EditText pool_Name;
    private EditText obs_Name;

    private Spinner spinner_pool;


    private ImageView btn_forward;
    private ImageView btn_back;
    private ImageView btn_left;
    private ImageView btn_right;
    private Button btn_stop;
    private int count1;
    private int count2;
    private String name;

    private TextView text_speed;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.paint_map_activity);
        id = DeviceName.getDeviceInstance().getDeviceId().get(0);
        SharedPreferences preferences = getSharedPreferences("data", MODE_PRIVATE);
        String userName = preferences.getString("userName", "");

        ListView listViewPool = findViewById(R.id.ListView_poolPoint);
        ListView listViewObs = findViewById(R.id.ListView_obsPoint);
        initView();
        initSpinner(userName);
        moveControl();


        //创建一个池塘
        createPool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!pool_Name.getText().toString().equals("")) {
                    poolName = pool_Name.getText().toString();

                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(PaintMap.this);
                    builder.setTitle("提示：");
                    builder.setMessage("请先输入池塘名称");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
            }
        });

        //创建一个障碍物
        createObs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!obs_Name.getText().toString().equals("")) {
                    obsName = obs_Name.getText().toString();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(PaintMap.this);
                    builder.setTitle("提示：");
                    builder.setMessage("请先输入障碍物名称");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }

            }
        });

        //添加边界点
        btn_insert_poolPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count1++;

                Call<JsonRootBean> call1 = appNetService.postMonitor(id);
                call1.enqueue(new Callback<JsonRootBean>() {
                    @Override
                    public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
                        System.out.println(response.toString());
                        JsonRootBean jsonRootBean = response.body();
                        Data monitorData = jsonRootBean.getData().get(0);
                        String X = monitorData.getX_coordinate();
                        String Y = monitorData.getY_coordinate();
                        poolList.add(new PoolPoint(count1, true, X, Y));
                        initListView(listViewPool, poolList);


                    }

                    @Override
                    public void onFailure(Call<JsonRootBean> call, Throwable t) {
                        Log.d(TAG, "onFailure: " + t.toString());
                    }
                });


                System.out.println(poolList.toString());

            }
        });

        //添加障碍点
        btn_insert_obsPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count2++;
                Call<JsonRootBean> call1 = appNetService.postMonitor(id);
                call1.enqueue(new Callback<JsonRootBean>() {
                    @Override
                    public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
                        System.out.println(response.toString());
                        JsonRootBean jsonRootBean = response.body();
                        Data monitorData = jsonRootBean.getData().get(0);
                        String X = monitorData.getX_coordinate();
                        String Y = monitorData.getY_coordinate();
                        obsList.add(new PoolPoint(count2, false, X, Y));
                        initListView(listViewObs, obsList);

                    }

                    @Override
                    public void onFailure(Call<JsonRootBean> call, Throwable t) {
                        Log.d(TAG, "onFailure: " + t.toString());
                    }
                });


            }
        });

        //提交边界点
        btn_subPoint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringBuilder str = new StringBuilder();
                for (PoolPoint poolPoint :
                        poolList) {
                    str.append(poolPoint.getPoint_X());
                    str.append(",");
                    str.append(poolPoint.getPoint_Y());
                    str.append(";");
                }
                Call<ResponseBody> addBoundary = appNetService.postAddBoundary(poolName, "Boundary", str.toString(), userName);
                addBoundary.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Toast.makeText(getApplication(), "添加池塘成功", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(getApplication(), "添加池塘失败", Toast.LENGTH_SHORT).show();
                        t.printStackTrace();
                    }
                });

                poolList.clear();
                initListView(listViewPool, poolList);

                count1 = 0;
                pool_Name.setText("");

                initSpinner(userName);
                System.out.println("更新池塘");
            }
        });

        //提交障碍点
        btn_subObs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                StringBuilder str = new StringBuilder();
                for (PoolPoint poolPoint :
                        obsList) {
                    str.append(poolPoint.getPoint_X());
                    str.append(",");
                    str.append(poolPoint.getPoint_Y());
                    str.append(";");
                }


                ObstaclesPoint obstaclesPoint = new ObstaclesPoint(obsName, str.toString(), name, obsName, userName);
                System.out.println(obstaclesPoint.toString());

                Call<ResponseBody> responseBodyCall = appNetService.postAddObstacles(obstaclesPoint);
                responseBodyCall.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Toast.makeText(getApplication(), "添加障碍点成功", Toast.LENGTH_SHORT);
                        obsList.clear();
                        initListView(listViewObs, obsList);
                        count2 = 0;
                        obs_Name.setText("");
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Toast.makeText(getApplication(), "添加障碍点失败", Toast.LENGTH_SHORT);
                    }
                });


                count1 = 0;
                pool_Name.setText("");

            }
        });

    }

    private void initListView(ListView listViewPool, List<PoolPoint> poolList) {
        PoolPointAdapter adapter1 = new PoolPointAdapter(PaintMap.this, R.layout.pool_point_item, poolList);
        listViewPool.setAdapter(adapter1);
        adapter1.notifyDataSetChanged();
    }

    private void moveControl() {
        manualBody.clear();
        //手动控制指令
        btn_forward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                manualBody.setLeftWheelAdd();
                manualBody.setRightWheelAdd();
                sendManualCm(id);
            }
        });

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setLeftWheelDelete();
                manualBody.setRightWheelDelete();
                sendManualCm(id);
            }
        });

        btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setRightWheelAdd();
                sendManualCm(id);

            }
        });

        btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manualBody.setLeftWheelAdd();
                sendManualCm(id);
            }
        });

        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manualBody.clear();
                Call<ResponseBody> call = appNetService.postStop(id);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Log.d(TAG, "onResponse: " + response);
                        updateSpeed();
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });

            }
        });

    }

    private void sendManualCm(String id) {
        manualBody.setDevice_name(id);
        Log.d(TAG, "sendManualCm: " + manualBody.toString());
        Call<ResponseBody> call = appNetService.postManualControl(manualBody);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d(TAG, "onResponse: " + response);
                updateSpeed();
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void updateSpeed() {
        String left_wheel = manualBody.getLeft_wheel();
        String right_wheel = manualBody.getRight_wheel();
        text_speed.setText(String.format("%s ! %s", left_wheel, right_wheel));
    }

    private void initSpinner(String userName) {

        //获取池塘名列表
        Call<PoolName> poolNameCall = appNetService.postFindPoolNameBU(userName);
        poolNameCall.enqueue(new Callback<PoolName>() {
            @Override
            public void onResponse(Call<PoolName> call, Response<PoolName> response) {
                PoolName poolName = response.body();
                List<String> poolName_list = new ArrayList<>();
                //防止返回的数据中有空数据
                for (String data :
                        poolName.getData()) {
                    if (data != null) {
                        poolName_list.add(data);
                    }
                }

                initPoolSpinner(poolName_list, spinner_pool);
            }

            @Override
            public void onFailure(Call<PoolName> call, Throwable t) {

            }
        });


    }

    private void initPoolSpinner(List<String> poolList, Spinner spinner_poolName) {
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, poolList);
        //设置样式
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner_poolName.setAdapter(arrayAdapter);
        //为Spinner设置选中事件监听器
        spinner_poolName.setOnItemSelectedListener(PaintMap.this);
    }

    private void initView() {

        btn_insert_poolPoint = findViewById(R.id.btn_insert_poolPoint);
        btn_insert_obsPoint = findViewById(R.id.btn_insert_obsPoint);
        btn_subPoint = findViewById(R.id.btn_subPoint);
        btn_subObs = findViewById(R.id.btn_subObs);
        btn_forward = findViewById(R.id.btn_forward);
        btn_back = findViewById(R.id.btn_back);
        btn_left = findViewById(R.id.btn_left);
        btn_right = findViewById(R.id.btn_right);
        btn_stop = findViewById(R.id.btn_stop2);
        text_speed = findViewById(R.id.text_speed2);

        createPool = findViewById(R.id.btn_addNewPool);
        createObs = findViewById(R.id.btn_addNewObs);

        pool_Name = findViewById(R.id.text_poolName3);
        obs_Name = findViewById(R.id.text_obsName);

        spinner_pool = findViewById(R.id.spinner_poolName3);
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String data = parent.getItemAtPosition(position).toString();
        System.out.println("data" + data);
        TextView tv1;
        TextView tv2;

        switch (parent.getId()) {
            case R.id.spinner_poolName3:
                name = data;
                tv1 = (TextView) view;
                //tv1.setTextColor(getResources().getColor(R.color.colorBlack));
                break;
            default:
                break;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}